package com.rzgeo.wcgallay.util;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;

import com.rzgeo.wcgallay.model.WcmSysFolder;

import java.io.File;
import java.util.ArrayList;

/**
 * Created by zhanghang on 2017/11/29.
 */

public class WcmEnv {


    public static final String[] Promssion = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.INTERNET,
            Manifest.permission.ACCESS_FINE_LOCATION,
    };



    private static final int SDK_PERMISSION_REQUEST = 127;
    private static WcmEnv _inst;
    private Activity _activity;
    private OnInitialized _onInitialized;
    private WcmSysFolder _sysFolder;

    public static WcmEnv getDefaultInst() {
        if (_inst == null) {
            _inst = new WcmEnv();
        }
        return _inst;
    }

    public WcmSysFolder getAppStandFolder() {
        if(_sysFolder==null){
            _sysFolder =new WcmSysFolder(new File(
                    Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "WCM"));
        }
        return _sysFolder;
    }

//    private String getWorksFolder() {
//        return getAppStandFolder() + File.separator + "works";
//    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        boolean pass = true;
        for (int r : grantResults) {
            if (r != PackageManager.PERMISSION_GRANTED)
                pass = false;
        }

        if (pass) {
            DoInit();
            _onInitialized.Pass();
        } else {
            new AlertDialog.Builder(_activity).setTitle("注意").
                    setMessage("以上权限是系统运行必须的，请重启程序并同意授权").
                    setPositiveButton("马上重启", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            Intent intent = _activity.getPackageManager()
                                    .getLaunchIntentForPackage(_activity.getPackageName());
                            PendingIntent restartIntent = PendingIntent.getActivity(_activity, 0, intent, PendingIntent.FLAG_ONE_SHOT);
                            AlarmManager mgr = (AlarmManager) _activity.getSystemService(Context.ALARM_SERVICE);
                            mgr.set(AlarmManager.RTC, System.currentTimeMillis(), restartIntent); // 1秒钟后重启应用
                            System.exit(0);
                        }
                    }).setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    System.exit(0);
                }
            })
                    .show();
        }
    }

    private void DoInit() {


    }

    public void init(Activity activity, OnInitialized onInitialized) {
        _onInitialized = onInitialized;
        _activity = activity;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getPersimmions();
        } else {
            _onInitialized.Pass();
        }
    }

    @TargetApi(23)
    private void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            /***
             * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
             */
            ArrayList<String> permissions2Require = new ArrayList<>();
            for (String pro : Promssion) {
                if (_activity.checkSelfPermission(pro) != PackageManager.PERMISSION_GRANTED) {
                    permissions2Require.add(pro);
                }
            }

            if (permissions2Require.size() > 0) {
                _activity.requestPermissions(permissions2Require.toArray(new String[permissions2Require.size()]), SDK_PERMISSION_REQUEST);
            } else {
                _onInitialized.Pass();
            }
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (_activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (_activity.shouldShowRequestPermissionRationale(permission)) {
                return true;
            } else {
                permissionsList.add(permission);
                return false;
            }
        } else {
            return true;
        }
    }

    public Context getApplicationContext() {
        return _activity.getApplicationContext();
    }

    public final boolean isDebug() {
        return false;
    }

    public interface OnInitialized {
        void Pass();

        void Fail();
    }

}
